﻿using System;
using System.Linq;
using System.Windows.Forms;
using Crm2011.Framework.Core;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Services;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;



namespace Crm2011.Framework.Connect
{
    /// <summary>
    /// This connection control allows the user to edit 
    /// a Microsoft Dynamisc CRM connection using a LiveId. 
    /// </summary>
    /// <seealso cref="http://deepakexploring.wordpress.com/2011/02/16/crud-operation-early-bound-classes-using-wcf-services-in-crm-2011/" />
    /// <seealso cref="http://charlesemes.blogspot.com.es/2011/03/connecting-to-crm-2011-cloud.html" />
    /// <seealso cref="http://social.microsoft.com/Forums/en/crmdevelopment/thread/2d97836b-75eb-4f77-a568-c6a87e429ef7" />
    public partial class LiveIdConnectionControl : UserControl, ICrmConnectionControl
    {
        public LiveIdConnectionControl()
        {
            InitializeComponent();
            _errorProviders = new ErrorProviderCollection(this);

            _textDeviceId = "123456789012345";
            _textDevicePassword = "0123456789ABCDEF";
        }



        private readonly ErrorProviderCollection _errorProviders;
        private string _textDevicePassword;
        private string _textDeviceId;



        /// <summary>
        /// Gets the CRM connection string based on the controls.
        /// </summary>
        /// <returns></returns>
        CrmConnectionString ICrmConnectionControl.GetCrmConnectionString()
        {
            return new CrmConnectionString
                {
                    Server = textWebApplicationUrl.Text,
                    UserId = textUsername.Text,
                    Password = textPassword.Text,
                    DeviceId = _textDeviceId,
                    DevicePassword = _textDevicePassword,
                    AuthenticationType = AuthenticationProviderType.ActiveDirectory
                };
        }



        /// <summary>
        /// Sets the CRM connection string and populates the controls accordingly
        /// </summary>
        /// <param name="value">The value.</param>
        void ICrmConnectionControl.SetCrmConnectionString(CrmConnectionString value)
        {
            CrmConnectionString crmConnectionString = value ?? new CrmConnectionString();
            textUsername.Text = crmConnectionString.UserId;
            textPassword.Text = crmConnectionString.Password;
            _textDeviceId = crmConnectionString.DeviceId;
            _textDevicePassword = crmConnectionString.DevicePassword;
            textWebApplicationUrl.Text = crmConnectionString.Server;
        }


        #region UI Event-Handlers


        private void btnConnect(object sender, EventArgs e)
        {
            _errorProviders.ClearAllErrors();
            try
            {
                CrmConnectionString crmConnectionString = ((ICrmConnectionControl) this).GetCrmConnectionString();
                CrmConnection crmConnection = CrmConnection.Parse(crmConnectionString.GetConnectionStringClearText());
                IOrganizationService orgService = new OrganizationService(crmConnection);

                using (var context = new ServiceContext(orgService))
                {
                    Guid userid = ((WhoAmIResponse) orgService.Execute(new WhoAmIRequest())).UserId;
                    SystemUser me = context.SystemUserSet.FirstOrDefault(su => su.Id == userid);
                    textCrmUsername.Text = me.FullName;
                }
            }
            catch (Exception exception)
            {
                _errorProviders.SetError(this.btnConnectDiscovery, exception.Message + (exception.InnerException != null ? Environment.NewLine + exception.InnerException.Message : ""));
            }
        }


        #endregion
    }
}